#region Using directives
using System;
using Microsoft.DirectX;
using SharpWind.Helpers;
using System.Collections.Generic;
using System.Text;
using SharpWind.Resources;
#endregion

namespace SharpWind.Resources.Sound
{
	public class SoundManager : ResourceManager<SoundObject>
	{
		#region Fields

		private Listener listener = null;

		#endregion

		#region Methods

		public override bool Initialize( Log log, Settings settings )
		{
			this.log = log;
			this.settings = settings;
			this.listener = new Listener();

			bool result = FreeSL.fslInit( settings.SoundSystem );
			if( result )
			{
				FreeSL.fslInitSourceManager( MaxSources );
				FreeSL.fslSetMetersPerUnit( settings.Scale );
			}

			return result;
		}

		public SoundObject Load( string package, string name )
		{
			if( !string.IsNullOrEmpty( name ) && !this.resources.ContainsKey( name ) )
			{
				SoundObject resource = new SoundObject();
				if( resource.Load( package, name ) )
				{
					this.resources.Add( name, resource );

					return resource;
				}
			}

			return null;
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				FreeSL.fslShutDownSourceManager();
				FreeSL.fslShutDown();
			}
		}

		private void LogError( string message, bool isCritical )
		{
			if( isCritical )
			{
				log.WriteWarning( "Sound", message );
			}
			else
			{
				log.WriteError( "Sound", message );
			}
		}

		#endregion

		#region Properties

		public Listener Listener
		{
			get
			{
				return this.listener;
			}
		}

		public float Volume
		{
			set
			{
				FreeSL.fslSetVolume( value );
			}
		}

		public int TotalSounds
		{
			get
			{
				return FreeSL.fslCountSoundsTotal();
			}
		}

		public int FreeSlots
		{
			get
			{
				return FreeSL.fslSourceManagerCountFreeSlots();
			}
		}

		public int MaxSources
		{
			get
			{
				return FreeSL.fslGetMaxSources();
			}
		}

		public string MemoryUsage
		{
			get
			{
				float size	= (float)FreeSL.fslGetSoundMemoryUsage();
				string unit = "B";

				if( size > 1024 )
				{
					size /= 1024;
					unit = "kB";
				}

				if( size > 1024 )
				{
					size /= 1024;
					unit = "MB";
				}

				if( size > 1024 )
				{
					size /= 1024;
					unit = "GB";
				}

				return string.Format( "{0} {1}", size, unit );
			}
		}

		#endregion
	}
}